// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()

exports.main = async (event, context) => {
    var event_ojb = (Buffer.from(event.body, 'base64')).toString()
    event_ojb = JSON.parse(event_ojb)
    console.log("输入参数", event_ojb)
    if (event_ojb.operation != "query_file" || event_ojb.typed == null) {
        console.log("无效参数")
        return {
            ret: "无效参数"
        }
    }

    if (event_ojb.operation == "query_file") {
        if (event_ojb.typed == "all") {
            const todosCollection = await db.collection('tuya_license').count()
            console.log("授权码文件总数", todosCollection)
            const tasks = []
            tasks.push(await db.collection('tuya_license').get())
            const al = await Promise.all(tasks)
            var file = []
            for (let i = 0; i < al[0].data.length; i++) {
                file.push(al[0].data[i].file)
            }
            return file
        } else {
            //用文件名找记录
            const get_id = await db.collection('tuya_license').where({
                file: event_ojb.typed
            }).get()

            if (get_id.data.length == 0) {
                return {
                    ret: "找不到文件"
                }
            }

            return get_id.data[0].license
        }
    }

    return {
        ret: "无效操作"
    }
}